package cc.sjfx.sharedoc.db;

import java.io.Serializable;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import cc.sjfx.sharedoc.db.bmob.User;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.mandroid.frame.toast.MLog;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;

@Table(name = "User")
public class UserDB extends Model implements Serializable{
	@Column(name = "NickName")
	public String nickName;
	@Column(name = "Ico")
	public String ico;
	@Column(name = "Username", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
	public String username;

	@SuppressWarnings("null")
	public static synchronized UserDB getUserDB(Context context, String username) {
		UserDB db;
		db = new Select().from(UserDB.class).where("Username  = ?", username)
				.executeSingle();
		if (db != null) {
			return db;
		}
		MLog.i("DBNull");
		db = new UserDB();
		db.username = username;
		db.save();
	//	getUserData(context, username);
		return db;
	}
	public static  List<UserDB> getUserDB(){
		List<UserDB> list=new Select().from(UserDB.class).execute();
		return list;
	}
	private static void setData(String username, User user, WebDataCallBack callBack) {
		UserDB db = new Select().from(UserDB.class)
				.where("Username  = ?", username).executeSingle();
		db.username = username;
		db.nickName = user.getNickName();
		db.ico = user.getIcoName();
		db.save();
		callBack.getIco(user.getIcoName());
	}
	public static void updateData(final Context context,JSONObject jObject) throws JSONException{
		String username=jObject.getString("username");
		String nickName=jObject.getString("nickName");
		String ico=jObject.getString("icoName");
		UserDB db = new Select().from(UserDB.class)
				.where("Username  = ?", username).executeSingle();
		db.username = username;
		db.nickName = nickName;
		db.ico = ico;
		db.save();
	}
	public static void getUserData(final Context context, final String username,final WebDataCallBack callBack) {
		// TODO Auto-generated method stub
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereEqualTo("username", username);
		query.findObjects(context, new FindListener<User>() {
			@Override
			public void onSuccess(List<User> arg0) {
				// TODO Auto-generated method stub
				if (arg0.size() != 0) {
					setData(username, arg0.get(0),callBack);
				}
			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stub

			}
		});
	}
	public interface WebDataCallBack{
		public void getIco(String img);
	}
}
